<template>
  <Container class="role-edit">
    <div class="container-header title title-center" slot="header">
      {{ title }}
      <Button size="large" class="fl btn-back"  icon="ios-arrow-back" @click="jumpPrevPage">返回</Button>
    </div>
    <div class="bg-light pt clear mb">
      <Form :label-width="80" :model="form" ref="form" :rules="ruleValidate">
        <FormItem label="角色名称" prop="name">
          <Input :maxlength="20" class="wp40" :disabled="type == 2" v-model.trim="form.name" placeholder="请输入2-20位字符的角色名称"/>
        </FormItem>
        <FormItem label="描述" prop="description">
          <Input :maxlength="200" class="wp40" :disabled="type == 2"  v-model.trim="form.description" :rows="2" type="textarea" placeholder="对角色的描述"/>
        </FormItem>
        <!-- <FormItem label="是否是部门">
          <Checkbox v-model="form.is_department"></Checkbox>
        </FormItem> -->
      </Form>
    </div>
    <div class="bg-light pt clear mb">
      <Tree ref="tree" :disabled="true" :data="data2" show-checkbox @on-check-change="onCheckChange"></Tree>
    </div>
    <Loader :status="status" @refresh="getInfo"></Loader>
    <div class="container-footer bg-white" slot="footer">
      <div v-if="!isSystem">
        <Button type="primary" class="mr" size="large" :disabled="type == 2" @click="onSave">确定</Button>
      </div>
      <div v-else>
        <Tooltip>
          <Button type="primary" class="mr" size="large" :disabled="isDisabled">确定</Button>
          <div slot="content">
            <p>提示：</p>
            <p>因规则原因无法编辑系统内置角色</p>
          </div>
        </Tooltip>
      </div>
    </div>
  </Container>
</template>
<script>
export default {
  data() {
    const validateName = (rule, value, callback) => {
      if (value.trim() === '') {
        callback(new Error('请输入角色名称'))
      } else {
        if (value.length < 2) {
          callback(new Error('角色名称在2-20个字之间'))
        }
        callback()
      }
    }
    return {
      data2: [],
      id: this.$route.query.id || '',
      title: '',
      status: 'pass',
      isSystem: false,
			isDisabled: false,
      form: {
				name: '',
        description: '',
        // is_department: false
      },
      toStageData: {},
      ruleValidate: {
        name: [{ required: true, validator: validateName, trigger: 'blur' }],
        description: [{ required: true, message: '请输入描述内容', trigger: 'blur' }]
      },
      selectCheck: [], //现在勾选的权限id
      getCheck: [], //原来的选中权限id,
      type: this.$route.query.type || ''
    }
  },
  mounted() {
    this.getTree()
    this.$refs.form.resetFields()
    if (this.id) {
      this.title = '编辑角色'
    } else {
      this.title = '新增角色'
    }
  },
  methods: {
    getInfo() {
			this.status = 'loading'
      this.$ajaxGet(`/role/roleInfo`, {role_id: this.id}).then(data => {
        this.form.name = data.role_info.name
        this.form.description = data.role_info.remark
        // this.form.is_department = data.role_info.is_department == 1 ? true : false
        this.selectCheck = data.role_rule_list
        // if (data.isSystem) {
        //   this.isDisabled = true
        //   this.isSystem = true
        // } else {
        //   this.isSystem = false
        // }
        this.data2.forEach(item => {
          item.children.forEach(itemFirst => {
            data.role_rule_list.forEach(resChild => {
              if (itemFirst.children.length) {
                itemFirst.children.forEach(itemSecond => {
                  if (resChild === itemSecond.id) itemSecond.checked = true
                })
              } else {
                if(itemFirst.id == resChild) itemFirst.checked = true
              }
            })
          })
        })
        this.status = 'pass'
      }).catch(() => {
        this.status = 'error'
      })
    },
    getTree() {
      this.$ajaxGet('/menu/authRule').then(data => {
        this.data2 = (data || []).map((item) => {
          return {
            id: item.id,
            title: item.title,
            expand: true,
            checked: false,
            disabled: this.type == 2 ? true : false,
            children: (item.child || []).map(firstChild => {
              return {
                id: firstChild.id,
                title: firstChild.title,
                expand: true,
                checked: firstChild.viewUrl == '/home/user/edit' ? true : false,
                disabled: this.type == 2 ? true : false,
                children: (firstChild.child || []).map(secondChild => {
                  return {
                    id: secondChild.id,
                    title: secondChild.title,
                    disabled: this.type == 2 ? true : false,
                    checked: secondChild.id == '100101' ? true : false
                  }
                })
              }
            })
          }
        })
        if(this.id) {
          this.getInfo()
        }
      })
    },
    onCheckChange() {
      this.getSelectedNodes()
    },
    getSelectedNodes() {
      this.selectCheck = this.$refs.tree.getCheckedAndIndeterminateNodes().map((item) => {
        return item.id
      })
    },
    onSave() {
      if (this.isDisabled) return
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.selectCheck.length == 0) {
            this.$Message.error('请选择权限')
            return
          }
					this.toStageData.role_name = this.form.name
          this.toStageData.role_remark = this.form.description
          // this.toStageData.is_department = this.form.is_department ? 1 : 0
          this.toStageData.rule_ids = this.selectCheck ? this.selectCheck.join(',') : this.getCheck
          this.isDisabled = true
          let url = this.id ? '/role/editRole' : '/role/addRole'
          let text = this.id ? '编辑' : '新增'
          if(this.id)	this.toStageData.role_id = this.id
          this.status = 'loading'
          this.$jsonPost(url, this.toStageData).then(data => {
            this.status = 'pass'
            this.$Notice.success({
              title: `${text}成功`
            })
            this.$router.push('/setting/role/list')
          }).catch(() => {
            this.isDisabled = false
          })
        }
      })
    },
    jumpPrevPage() {
      this.$router.back()
    }
  }
}
</script>